package com.library.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.library.entity.Student;

import my.db.Page;
import my.db.QueryHelper;

public class StudentDao {

	
	//根据账号查询
	public Student findByName(String uname) {
		String sql = "select * from student where uname=?";
		return QueryHelper.queryUnique(Student.class, sql, uname);
	}
	
	//保存
	public void save(Student s) {
		String sql = "insert into student values(null,?,?,?,?,?)";
		QueryHelper.update(sql, s.getName(), s.getUname(),s.getPasswd(),s.getSex(),s.getCtime());
	}
	
	// 修改
	public void update(Student s) {
		String sql = "update student set name=?,uname=?,sex=?,ctime=? where id=?";
		QueryHelper.update(sql, s.getName(), s.getUname(),s.getSex(),s.getCtime(), s.getId());
	}
	
	// 删除
	public void delete(long id) {
		String sql = "delete from student where id=?";
		QueryHelper.update(sql, id);
	}
	
	/**
	 * 根据ID查询
	 * */
	public Student get(long id) {
		String sql = "select * from student where id=?";
		return QueryHelper.queryUnique(Student.class, sql, id);
	}
	
	/**
	 * 分页查询
	 * */
	public Page<Student> findPage(Page<Student> page, String name) {
		List<Object> params = new ArrayList<>();
		String sql = "select * from student";
		if(StringUtils.isNotBlank(name)) {
			sql += " where name like ?";
			params.add("%"+name+"%");
		}
		if(StringUtils.isNotBlank(page.getField())) {
			sql += String.format(" order by %s %s", page.getField(), page.getType());
		}
		
		List<Student> data = QueryHelper.queryPage(Student.class, sql, page.getPage(), page.getLimit(), params.toArray());
		page.setData(data);
		
		String sql2 = sql.replaceFirst("select .*? from", "select count(*) from");
		Long cnt = QueryHelper.stat(sql2, params.toArray());
		page.setCount(cnt);			
		
		return page;
	}
}
